package com.example.common.core.common;

import com.example.common.core.ex.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/10/10
 * @desc
 */
@Component
public class JwtUtils {

    @Value("${token.expire}")
    private Integer expire;

    @Value("${token.secret}")
    private String secret;


    public String createToken(HashMap<String, Object> map) {
        long expire = System.currentTimeMillis() + this.expire * 60 * 1000;
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new Date(expire))
                .addClaims(map);
        String token = jwtBuilder.compact();
        return token;
    }

    public Claims parseToken(String token) {
        Claims claims = null;
        // try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        // } catch (Exception e) {
        //     e.printStackTrace();
        //     throw new BusinessException("令牌解析出错!");
        // }
        return claims;
    }

}
